#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from project.flasky import db
from project.define import db_logger


DataName = "收费处"
TableName = "app_device_cashier"


class DeviceCashier(db.Model):
    """
    收费处
    """
    __tablename__ = TableName
    DeviceID = db.Column(db.String(128), primary_key=True, nullable=False)
    # 收费处名稱
    CashierName = db.Column(db.String(128), nullable=False, unique=True)
    # 设备地址
    CashierAddr = db.Column(db.String(32), nullable=False, unique=True)
    # 位置
    Position = db.Column(db.String(32))
    # 服务版本
    Version = db.Column(db.String(8))
    
    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.DeviceID = kwargs.get('DeviceID')
        self.CashierName = kwargs.get('CashierName')
        self.CashierAddr = kwargs.get('CashierAddr')
        self.Position = kwargs.get('Position')

    def to_dict(self):
        """
        转换键值对
        """
        return dict([(c.name, getattr(self, c.name)) for c in self.__table__.columns])

    @staticmethod
    def current_datas():
        """
        当前闸机
        """
        datas = DeviceCashier.query.all()
        if datas:
            return [i.to_dict() for i in datas]
        return []

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {'DeviceID':'設備編號', 'CashierName': '名稱', 'CashierAddr': 'IP地址', 'Position': '位置', 'Version':'服務版本'}
        return ColumnName

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        device_id = kwargs.get('DeviceID')
        if device_id:
            return DeviceCashier.query.filter_by(DeviceID=device_id).first()

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(DeviceCashier, k):
                    if k == 'CashierName':
                        filters.add(DeviceCashier.CashierName == v)
                    elif k == 'Position':
                        filters.add(DeviceCashier.Position.like(f"%{v}%"))
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = DeviceCashier(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = DeviceCashier.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}D成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            r = DeviceCashier.selected_data(**kwargs)
            if r:
                refresh = False
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            refresh = True
                if refresh:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
                else:
                    return "ignore"
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")

    @staticmethod
    def table_init():
        """
        数据初始化
        """
        demo_data = [
            {'DeviceID':'test1', 'CashierName': '收費處A', 'CashierAddr': '192.168.0.50'},
            {'DeviceID':'test2', 'CashierName': '收費處B', 'CashierAddr': '192.168.0.51'},
        ]
        for i in demo_data:
            address = i.get('CashierAddr')
            if address:
                r = DeviceCashier.query.filter_by(CashierAddr=address).first()
                if not r:
                    DeviceCashier.insert_data(**i)